package com.mida.dms.knw.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mida.dms.knw.util.MybatisInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@DependsOn("loadFromDatabasePropertyConfig")
@MapperScan(basePackages = DTMapping.PACKAGE,sqlSessionFactoryRef="dt_SqlSessionFactory")
public class DTMapping {
	
	static final String PACKAGE = "com.mida.dms.knw.mapper";
//	static final String MAPPER_LOCATION = "classpath*:com/ats/dt/Mapper/*.xml";
	static final String MAPPER_LOCATION = "classpath*:mssql/mapper/*.xml";
//	static final String MAPPER_LOCATION = "classpath*:oracle/mapper/*.xml";

	@Value("${dataelement.url}")
	private String url;

	@Value("${dataelement.username}")
	private String user;

	@Value("${dataelement.passwd}")
	private String password;

	@Value("${dataelement.driver}")
	private String driverClass;
	
	@Value("${dataelement.dbType}")
	private String dbType;

	@Bean(name = "DTDataSource")
	public DataSource dtdDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(url.trim());
		dataSource.setDriverClassName(driverClass.trim());
		dataSource.setUsername(user.trim());
		dataSource.setPassword(password.trim());
		return dataSource;
	}

	
	/**
	 * 实例化数据源事务管理器
	 * 
	 * @return
	 */
	@Bean(value="dtdTxManager")
	public DataSourceTransactionManager dtdTxManager() {
		return new DataSourceTransactionManager(dtdDataSource());
	}

	
	
	@Bean(name="dt_SqlSessionFactory")
	public SqlSessionFactoryBean dtsqlSessionFactory() throws IOException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dtdDataSource());
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setCallSettersOnNulls(true);
		sqlSessionFactoryBean.setConfiguration(configuration);
		
		Interceptor[] interceptors= {new MybatisInterceptor()};
		sqlSessionFactoryBean.setPlugins(interceptors);
		
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));
		sqlSessionFactoryBean.setTypeAliasesPackage("com.mida.dms.knw.entity");
		return sqlSessionFactoryBean;
	}
}
